import { useUserStore } from '@/stores'
import type { App } from 'vue'
import { createRouter, createWebHistory, type RouteMap } from 'vue-router'
import {
  routes,
  handleHotUpdate, 
} from 'vue-router/auto-routes'
export const IndexPage: keyof RouteMap = "IndexPage"
export const router = createRouter({
  history: createWebHistory(),
  routes,
})

// This will update routes at runtime without reloading the page
if (import.meta.hot) { 
  handleHotUpdate(router) 
}

router.beforeEach(async (to, __, next) => {
  const userStore = useUserStore()
  if (!to.meta.isPublic && isLogin() && !userStore.userInfo)
    await userStore.getUserInfo()
  if (to.name === "Login" && isLogin()) {
    return next({ name: IndexPage })
  }
  next()
})

export function setupRouter(app: App) {
  app.use(router)
}
export default router
